<?php

namespace App\Http\Middleware;

use App\Common\ErrorCode\ErrorCode;
use App\Exceptions\BusinessException;
use App\Http\Service\JwtServiceTest;
use App\Http\Service\UserService;
use Closure;
use Illuminate\Http\Request;
use Lcobucci\JWT\Token;
use App\Models\Admin\UserAccessModel;

//有用，判断提交之前或之后执行都动作是否满足要求，满足则执行对应方法，zwp
class WebTestCheckTokenMiddle
{
    /**
     * @param $request
     * @param Closure $next
     * @return mixed
     * @throws BusinessException
     */
    public function handle($request, Closure $next)
    {
        $token = $this->getToken($request);//获取token
        $uid = session("loginUser")->id;//登录后session里的用户id
        $type = session("loginUser")->type;//登录后的session里的type
        /*
        $uid = $request->uid;//获取提交来的uid，
        $type = $request->type;//获取request对象中提交来都type
        */
        if(!$token){
            $uid = 2;
            $type = 1;
            echo "token不对";
            exit();
        }else{
            
            if($this->validToken($token,$uid)){//验证token，zwp
                
                UserService::setUserInfo($uid, $type);
                //var_dump($type."***".$uid);exit();
                $request->attributes->add(['loginUid'=>$uid,'loginType'=>$type]);
                return $next($request);
            }else{
                //zwp,
                echo "非法提交";
                exit();//或者抛出错误提示，
                
            }

            
        }
        //var_dump($request->all());exit();
        
        
        
    }

    /**
     * 验证token
     * @param string $token, int $uid
     * @return bool 
     */
    public function validToken($token,$uid){
        $start = strtotime(date('Ymd').'000000');
        $end = strtotime(date('Ymd').'235959');
        
        $access_token = UserAccessModel::where('uid',$uid)
            ->where('created_at','>',$start)
            ->where('created_at','<=',$end)
            ->first();
        //取当天的token
        if(!$access_token||$uid==null){
            session(["uid"=>null,"token"=>null]);
            session()->save();
            return false;
        }
        if($token==$access_token->token){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获取token
     * @param Request $request
     * @return array|mixed|string
     * @throws BusinessException
     */
    private function getToken(Request $request)
    {
        $token = $request->cookie('token');
        if (empty($token)) {
            $token = $request->post('token');
        }
        if (empty($token)) {
            $token = $request->get('token');
        }
        return $token;
    }

    
}